import 'package:flutter/material.dart';
import 'joke.dart';
import 'random_joke_state.dart';

class HomeView extends StatefulWidget {
  const HomeView({super.key});

  @override
  State<HomeView> createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  RandomJokeState _state = const RandomJokeState(isLoading: true);

  @override
  void initState() {
    super.initState();
    _refresh(initialLoad: true);
  }

  Future<void> _refresh({bool initialLoad = false}) async {
    final previousJoke = _state.joke;
    final keepPrevious = !initialLoad && previousJoke != null;

    setState(() {
      _state = _state.copyWith(
        joke: keepPrevious ? previousJoke : null,
        error: null,
        isLoading: true,
        isRefreshing: keepPrevious,
      );
    });

    try {
      final joke = await fetchRandomJoke();
      if (!mounted) {
        return;
      }
      setState(() {
        _state = _state.copyWith(
          joke: joke,
          error: null,
          isLoading: false,
          isRefreshing: false,
        );
      });
    } catch (err) {
      if (!mounted) {
        return;
      }
      setState(() {
        _state = _state.copyWith(
          joke: keepPrevious ? previousJoke : null,
          error: err,
          isLoading: false,
          isRefreshing: false,
        );
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final state = _state;

    return Scaffold(
      appBar: AppBar(title: const Text('Random Joke Generator')),
      body: SizedBox.expand(
        child: Stack(
          alignment: Alignment.center,
          children: [
            if (state.isRefreshing)
              const Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: LinearProgressIndicator(),
              ),
            Builder(
              builder: (context) {
                if (state.isLoading && !state.hasJoke) {
                  return const CircularProgressIndicator();
                }

                if (state.hasError) {
                  return const Text('Error fetching joke');
                }

                if (state.hasJoke) {
                  final joke = state.joke!;
                  return SelectableText(
                    '${joke.setup}\n\n${joke.punchline}',
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 24),
                  );
                }

                return const SizedBox.shrink();
              },
            ),
            Positioned(
              bottom: 20,
              child: ElevatedButton(
                onPressed: () => _refresh(),
                child: const Text('Get another joke'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
